//
//  HPNetworkEngine.m
//  Network
//
//  Created by phq on 2019/7/4.
//  Copyright © 2019 phq. All rights reserved.
//

#import "HPNetworkEngine.h"

@implementation HPNetworkEngine

+ (HPNetworkEngine *)shareInstance {
    @synchronized (self) {
        static HPNetworkEngine *_manager = nil;
        static dispatch_once_t oncePredicate;
        dispatch_once(&oncePredicate, ^{
            _manager = [[HPNetworkEngine alloc] init];
            _manager.netConfig = [[HPNConfig alloc] init];
        });
        return _manager;
    }
}

#pragma mark -  post / get

- (void)httpsRequestPath:(NSString *)path
              parameters:(id)parameters
                 success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                 failure:(void (^)(NSURLSessionDataTask *task, NSError * error))failure {
    
    if ((path == nil || path.length == 0) && failure) {
        NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:@"parameter path is null", NSLocalizedDescriptionKey, @"The reason for failure:path is null", NSLocalizedFailureReasonErrorKey, @"Recovery advice:parameter path nonnull",NSLocalizedRecoverySuggestionErrorKey,nil];
        failure(nil,[[NSError alloc] initWithDomain:NSCocoaErrorDomain code:408 userInfo:info]);
        return;
    }
    
    // UTF8 encoding
    NSString *encodUrl = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = _netConfig.manager;
    // 获取HTTP headers
    NSDictionary *headers = manager.requestSerializer.HTTPRequestHeaders;
    if (_netConfig.requestMethod == RequestMethodGet) {
        [manager GET:encodUrl
          parameters:parameters
             headers:headers
            progress:nil
             success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 // This is on main thread
                 if (success) {
                     success(task,responseObject);
                 }
             }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 // This is on main thread
                 if (error && failure) {
                     failure(task,error);
                 }
             }];
    }else {
        [manager POST:encodUrl
           parameters:parameters
              headers:headers
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  // This is on main thread
                  if (success) {
                      success(task,responseObject);
                  }
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  // This is on main thread
                  if (error && failure) {
                      failure(task,error);
                  }
              }];
    }
}

#pragma mark - set http header

- (void)setHttpHeaderValue:(NSString *)value httpHeaderField:(NSString *)key {
    [_netConfig.manager.requestSerializer setValue:value forHTTPHeaderField:key];
}


#pragma mark - network status

/*
 AFNetworkReachabilityStatusUnknown          = -1,
 AFNetworkReachabilityStatusNotReachable     = 0,
 AFNetworkReachabilityStatusReachableViaWWAN = 1,
 AFNetworkReachabilityStatusReachableViaWiFi = 2,
 */
- (NSInteger)networkStatus {
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    return mgr.networkReachabilityStatus;
}

- (BOOL)isReachable {
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    return mgr.isReachable;
}

/**
 ******************************
 ******************************
 以下内容没开发完成
 */


#pragma mark - upload task
// 两种上传方式 ：http://blog.csdn.net/zhaocanrong/article/details/52513733
// 一、文件流的形式，（测试通过）
- (void)uploadImageWithName:(NSString *)fileName imageData:(NSData *)imageData url:(NSString *)url {
    
    //添加参数，根据实际情况使用
    //    NSMutableDictionary *parme = [NSMutableDictionary dictionary];
    //    parme[@"userId"] = [GDUserlnfo shareUser].userID;
    //    parme[@"image"] =imageData;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //若报错：Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
    // 是因为AFN不可接受的内容类型 “text/html”，
    //解决：
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
    //                                                         @"text/html",
    //                                                         @"image/jpeg",
    //                                                         @"image/png",
    //                                                         @"application/octet-stream",
    //                                                         @"text/json",nil];
    
    // 请求序列化器，不清楚怎样用
    //    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    // 请求失败可能服务器返回数据不是JSON,尝试更改解释方法调试请求是否正常
    //    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *urlString = url;
    // 获取HTTP headers
    NSDictionary *headers = manager.requestSerializer.HTTPRequestHeaders;
    [manager POST:urlString parameters:nil headers:headers constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /////传的图片数据放这里
        [formData appendPartWithFileData:imageData
                                    name:@"myFile" // myFile 是和后台商定的，后台用于查找图片的key
                                fileName:fileName // filename ：文件命名也是商定的。
                                mimeType:@"image/png"]; // image/png 是和后台商定的，一般是image/png 或 image/jpg
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSMutableDictionary *responseObject) {
        NSLog(@"********%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"===%@",error);
    }];
}


//二、转成NSData，在进行base64加密上传（没测试过）
- (void)uploadWithUrl:(NSString *)urlString filePath:(NSString *)filePathString {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURL *filePath = [NSURL fileURLWithPath:filePathString];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    [uploadTask resume];
}

@end
